"""
代码推荐系统演示脚本
展示如何使用基于Neo4j的代码推荐功能
"""

import os
import sys
import json
import time
from typing import Dict, List

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from code_recommender import CodeRecommender, get_driver


def print_separator(title: str):
    """打印分隔符"""
    print("\n" + "="*60)
    print(f"  {title}")
    print("="*60)


def print_recommendations(recommendations: List[Dict], title: str):
    """打印推荐结果"""
    print(f"\n📋 {title}")
    print("-" * 40)
    
    if not recommendations:
        print("❌ 没有找到推荐")
        return
    
    for i, rec in enumerate(recommendations, 1):
        print(f"{i:2d}. 📝 {rec['function_name']}")
        print(f"    📁 文件: {rec['function_file']}")
        print(f"    💡 理由: {rec['reason']}")
        
        if 'call_frequency' in rec:
            print(f"    📊 调用频率: {rec['call_frequency']}")
        if 'frequency' in rec:
            print(f"    📊 调用频率: {rec['frequency']}")
        if 'incoming_calls' in rec:
            print(f"    📊 被调用次数: {rec['incoming_calls']}")
        
        print()


def demo_function_recommendations(recommender: CodeRecommender):
    """演示函数推荐功能"""
    print_separator("函数推荐演示")
    
    # 测试不同的函数名
    test_functions = ["main", "process", "init", "create", "handle"]
    
    for func_name in test_functions:
        print(f"\n🔍 搜索函数: '{func_name}'")
        recommendations = recommender.get_function_recommendations(func_name, limit=3)
        print_recommendations(recommendations, f"'{func_name}' 的推荐函数")


def demo_next_function_calls(recommender: CodeRecommender):
    """演示下一个函数调用推荐"""
    print_separator("下一个函数调用推荐演示")
    
    test_functions = ["main", "process", "init"]
    
    for func_name in test_functions:
        print(f"\n🔍 当前函数: '{func_name}'")
        next_calls = recommender.get_next_function_calls(func_name, limit=3)
        print_recommendations(next_calls, f"'{func_name}' 可能调用的下一个函数")


def demo_function_signature_suggestions(recommender: CodeRecommender):
    """演示函数签名建议"""
    print_separator("函数签名建议演示")
    
    test_patterns = ["process", "create", "handle", "init"]
    
    for pattern in test_patterns:
        print(f"\n🔍 搜索模式: '{pattern}'")
        signatures = recommender.get_function_signature_suggestions(pattern, limit=3)
        print_recommendations(signatures, f"包含 '{pattern}' 的函数签名")


def demo_context_aware_recommendations(recommender: CodeRecommender):
    """演示上下文感知推荐"""
    print_separator("上下文感知推荐演示")
    
    # 模拟一些文件位置
    test_contexts = [
        ("src/main.cpp", 10),
        ("src/utils.cpp", 25),
        ("include/header.h", 5)
    ]
    
    for file_path, line_num in test_contexts:
        print(f"\n🔍 文件: {file_path}, 行号: {line_num}")
        recommendations = recommender.get_context_aware_recommendations(
            file_path, line_num, limit=3
        )
        print_recommendations(recommendations, f"位置 {file_path}:{line_num} 的上下文推荐")


def demo_popular_functions(recommender: CodeRecommender):
    """演示受欢迎函数推荐"""
    print_separator("受欢迎函数推荐演示")
    
    print("\n🔍 全局最受欢迎的函数:")
    popular = recommender.get_popular_functions(limit=5)
    print_recommendations(popular, "全局最受欢迎的函数")
    
    print("\n🔍 src/ 目录下最受欢迎的函数:")
    popular_src = recommender.get_popular_functions("src/", limit=3)
    print_recommendations(popular_src, "src/ 目录下最受欢迎的函数")


def demo_interactive_search(recommender: CodeRecommender):
    """演示交互式搜索"""
    print_separator("交互式搜索演示")
    
    while True:
        try:
            search_term = input("\n🔍 请输入要搜索的函数名 (输入 'quit' 退出): ").strip()
            
            if search_term.lower() in ['quit', 'exit', 'q']:
                break
            
            if not search_term:
                continue
            
            print(f"\n正在搜索 '{search_term}'...")
            
            # 获取函数签名建议
            signatures = recommender.get_function_signature_suggestions(search_term, limit=5)
            print_recommendations(signatures, f"包含 '{search_term}' 的函数")
            
            # 获取函数推荐
            recommendations = recommender.get_function_recommendations(search_term, limit=3)
            print_recommendations(recommendations, f"'{search_term}' 的推荐函数")
            
        except KeyboardInterrupt:
            print("\n\n👋 退出搜索")
            break
        except Exception as e:
            print(f"❌ 搜索出错: {e}")


def demo_api_usage():
    """演示API使用方式"""
    print_separator("API使用示例")
    
    api_examples = [
        {
            "title": "获取函数推荐",
            "method": "POST",
            "endpoint": "/recommendations/function",
            "body": {
                "function_name": "main",
                "context_file": "src/main.cpp",
                "limit": 10
            }
        },
        {
            "title": "获取下一个函数调用",
            "method": "POST", 
            "endpoint": "/recommendations/next-calls",
            "body": {
                "function_name": "process",
                "limit": 5
            }
        },
        {
            "title": "搜索函数",
            "method": "POST",
            "endpoint": "/search/functions", 
            "body": {
                "query": "init",
                "limit": 10
            }
        },
        {
            "title": "获取数据库统计",
            "method": "GET",
            "endpoint": "/stats",
            "body": None
        }
    ]
    
    for example in api_examples:
        print(f"\n📡 {example['title']}")
        print(f"   方法: {example['method']}")
        print(f"   端点: {example['endpoint']}")
        if example['body']:
            print(f"   请求体: {json.dumps(example['body'], indent=6, ensure_ascii=False)}")
        print()


def main():
    """主演示函数"""
    print("🚀 Neo4j代码推荐系统演示")
    print("=" * 60)
    
    # 检查Neo4j连接
    try:
        driver = get_driver()
        recommender = CodeRecommender(driver)
        
        # 测试连接
        with driver.session() as session:
            result = session.run("MATCH (f:Function) RETURN count(f) as count LIMIT 1")
            count = result.single()["count"]
            print(f"✅ 成功连接到Neo4j数据库，包含 {count} 个函数")
        
    except Exception as e:
        print(f"❌ 无法连接到Neo4j数据库: {e}")
        print("请确保:")
        print("1. Neo4j服务正在运行")
        print("2. 数据库中有导入的调用关系数据")
        print("3. 环境变量配置正确")
        return
    
    try:
        # 运行各种演示
        demo_function_recommendations(recommender)
        demo_next_function_calls(recommender)
        demo_function_signature_suggestions(recommender)
        demo_context_aware_recommendations(recommender)
        demo_popular_functions(recommender)
        demo_api_usage()
        
        # 交互式搜索
        print("\n" + "="*60)
        print("🎯 交互式搜索演示")
        print("="*60)
        print("现在你可以输入函数名进行实时搜索测试")
        
        demo_interactive_search(recommender)
        
    except Exception as e:
        print(f"❌ 演示过程中出错: {e}")
    
    finally:
        driver.close()
        print("\n👋 演示结束，感谢使用！")


if __name__ == "__main__":
    main()
